package com.example.concurrent.chapter06;

import java.util.concurrent.TimeUnit;

/**
 * @author Create By Liuqz
 * @date 2018/11/22 15:15
 * <p>
 * interrupt一个thread group 会导致该group中所有的active线程都被interrupt
 * 也就是说该group中的每一个线程的interrupt标识都被设置了
 */
public class ThreadGroupInterrupt {

    public static void main(String[] args) throws InterruptedException {
        ThreadGroup group = new ThreadGroup("TestGroup");

        new Thread(group, () -> {
            while (true) {
                try {
                    TimeUnit.MILLISECONDS.sleep(2);
                } catch (InterruptedException e) {
                    break;
                }
            }
            System.out.println("t1 will exit");
        }, "t1").start();

        new Thread(group, () -> {
            while (true) {
                try {
                    TimeUnit.MILLISECONDS.sleep(1);
                } catch (InterruptedException e) {
                    break;
                }
            }
            System.out.println("t2 will exit");
        }, "t2").start();

        TimeUnit.MILLISECONDS.sleep(2);

        /**
         * ThreadGroup.interrupt()
         * 会执行所有thread的interrupt方法,并且会递归获取子group,然后执行他们各自的interrupt方法
         */
        group.interrupt();

    }
}
